package com.ml4ai.core.stack.elasticsearch;

import lombok.Builder;
import org.elasticsearch.client.transport.TransportClient;
import org.elasticsearch.common.settings.Settings;
import org.elasticsearch.common.transport.TransportAddress;
import org.elasticsearch.transport.client.PreBuiltTransportClient;

import java.net.InetAddress;

/**
 * Created by leecheng on 2018/11/24.
 */
@Builder
public class ElasticSearchAgent {

    private String esServers;

    private String esCluster;

    private TransportClient client;

    public TransportClient getClient() throws Exception {
        if (client == null) {
            Settings settings = Settings.builder().put("cluster.name", esCluster).put("client.transport.sniff", "true").build();
            client = new PreBuiltTransportClient(settings);
            for (String host : esServers.split(",")) {
                String ip = host.split(":")[0];
                Integer prt = Integer.valueOf(host.split(":")[1]);
                client.addTransportAddress(new TransportAddress(InetAddress.getByName(ip), prt));
            }
        }
        return client;
    }

}
